package cn.jh.smartos.fragment

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import cn.jh.smartos.App
import cn.jh.smartos.BaseFragment
import cn.jh.smartos.R
import cn.jh.smartos.adapter.BaseAdapters
import cn.jh.smartos.adapter.BaseViewHolder
import cn.jh.smartos.adapter.MsgListAdapter
import cn.jh.smartos.adapter.Utils
import cn.jh.smartos.bean.ConnConfig
import cn.jh.smartos.bean.ConnConfig.socketItemList
import cn.jh.smartos.bean.MsgItem
import cn.jh.smartos.client.ClientService
import cn.jh.smartos.service.SimpleHttpServer
import cn.jh.smartos.utils.NetWorkKit
import cn.jh.smartos.utils.ToastU
import kotlinx.android.synthetic.main.activity_chat_ui.*
import kotlinx.android.synthetic.main.fragment_setting.*
import kotlinx.android.synthetic.main.im_bottom.*

/**
 * Created by pjh on 18/3/12.
 */
class MsgF : BaseFragment() {
    override fun getLayoutId(): Int = R.layout.activity_chat_ui
    private val TAG = "MsgF"
    private var mIntentFilter: IntentFilter? = null
    private var mReciver: MessageBackReciver? = null
    private var mAdapter: BaseAdapters? = null
    private var mMsgList: MutableList<MsgItem> = mutableListOf()
    private var sqlOffset = 0
    private var mLocalBroadcastManager: LocalBroadcastManager? = null
    override fun initView() {
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(App.context)
        mReciver = MessageBackReciver()
        mIntentFilter = IntentFilter()
        mIntentFilter?.addAction(ClientService.HEART_BEAT_ACTION)
        mIntentFilter?.addAction(ClientService.MESSAGE_ACTION)
        mIntentFilter?.addAction(SimpleHttpServer.SERVICE_STATE)
        mIntentFilter?.addAction(SimpleHttpServer.NEW_CLIENT)
        mReciver?.let { mIntentFilter?.let { it1 -> mLocalBroadcastManager?.registerReceiver(it, it1) } }
        initRefresh()
        getDBHistoryMsg()
        initEditListener()
        initAdapter()


    }

    override fun lazyLoad() {

    }

    val msgListAdapter = MsgListAdapter()
    private var mTitle: String? = null

    companion object {
        fun getInstance(title: String): MsgF {
            val fragment = MsgF()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mReciver?.let { mLocalBroadcastManager?.unregisterReceiver(it) }
    }



    private fun initRefresh() {
        refresh.setColorSchemeColors(ContextCompat.getColor(activity!!, R.color.colorAccent))
        refresh.setOnRefreshListener {
            if (sqlOffset < 20) {
                sqlOffset++
            }
            refresh.postDelayed({ refresh.isRefreshing = false }, 500)
        }
    }

    private fun initEditListener() {
        imChatInput.addTextChangedListener(object : TextWatcher {
            private var temp: CharSequence? = null

            override fun afterTextChanged(p0: Editable?) {
                if (temp.toString().isNullOrEmpty()) {
                    chat_send_btn.setTextColor(Color.parseColor("#CCCCCC"))
                    chat_send_btn.isClickable = false
                    img_select.visibility = View.VISIBLE
                    chat_send_btn.visibility = View.GONE
                } else {
                    chat_send_btn.setTextColor(Color.parseColor("#D63E3E"))
                    chat_send_btn.isClickable = true
                    img_select.visibility = View.GONE
                    chat_send_btn.visibility = View.VISIBLE
                    chat_send_btn.setOnClickListener {
                        sendMessage(temp.toString())
                    }

                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                temp = p0

            }

        })
    }

    /**
     * 模拟发送消息
     * */
    private fun sendMessage(msgString: String) {
        var input_msg = imChatInput.text.toString().trim()
        if (!input_msg.isNullOrEmpty()) {


            Log.e(TAG, "sendMessage : " + msgString)
            initAdapter()
//            refresh.postDelayed({ receiveMessage(input_msg) }, 500)

            if (ConnConfig.isService) {
                val socketService = SimpleHttpServer.getSocketService()
                if (socketService==null){
                    ToastU.showToast("相互连接以后才能发送")
                }else{
                    imChatInput.text.clear()
                    val msg = MsgItem(true, NetWorkKit.getLocalIpAddress(),msgString)
                    msg.time=System.currentTimeMillis().toString()
                    mMsgList.add(0, msg)
                    socketService.sendMessage(msgString)
                }
            } else {

                SettingF.iBackService?.sendMessage(msgString)
                imChatInput.text.clear()
                val msg = MsgItem(true, NetWorkKit.getLocalIpAddress(),msgString)
                msg.time=System.currentTimeMillis().toString()
                mMsgList.add(0, msg)
            }

        }
    }

    private fun initAdapter() {
        if (mAdapter == null) {
            mAdapter = object : BaseAdapters() {
                override fun onBindView(holder: BaseViewHolder, position: Int) {
                    var item_content = holder?.getView<TextView>(R.id.text_message) as TextView
                    var item_date = holder?.getView<TextView>(R.id.date) as TextView
                    var item_avatar = holder?.getView<ImageView>(R.id.avatar) as ImageView
                    var item_image = holder?.getView<ImageView>(R.id.img_message) as ImageView
                    var item_name = holder?.getView<ImageView>(R.id.name) as TextView

                    if (position > 0) {

                        if (position == mMsgList.size - 1) {
                            if (!TextUtils.isEmpty(mMsgList[position].time)){
                                item_date.visibility = View.VISIBLE

                                item_date.text = Utils.toDateDistance(mMsgList[position].time)
                            }
                        } else {

                        }

                    } else {
                        if (!TextUtils.isEmpty(mMsgList[position].time)){
                            item_date.visibility = View.VISIBLE

                            item_date.text = Utils.toDateDistance((java.lang.Long.parseLong(mMsgList[position].time)).toString())
                        }
                    }
                    item_name.text = mMsgList[position].id
                    Utils.showAvatar(item_avatar, mMsgList[position].id)
                    if (mMsgList[position].type == 1) {
                        item_content.text = mMsgList[position].content
                        item_content.visibility = View.VISIBLE
                        item_image.visibility = View.GONE

                    }
                }

                override fun getLayoutID(position: Int): Int {
                    return when {
                        mMsgList[position].isFrom -> R.layout.item_chat_send_layout
                        else -> R.layout.item_chat_rec_layout
                    }
                }

                override fun clickable(): Boolean {
                    return false
                }

                override fun getItemCount(): Int {
                    return mMsgList.size
                }

            }
            recycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, true)
            recycler.adapter = mAdapter
        } else {
            mAdapter?.notifyDataSetChanged()
        }
    }
    private var mExitTime: Long = 0


    /**
     * 历史消息
     */
    private fun getDBHistoryMsg() {
//        val history = DbUtils.getInstance().getHistoryMessage(sqlOffset)

        val history = MsgItem()
        history.time=System.currentTimeMillis().toString()
        mMsgList.add(0, history)
        initAdapter()
        recycler.scrollToPosition(mMsgList.size)
    }

    internal inner class MessageBackReciver() : BroadcastReceiver() {


        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {

                ClientService.HEART_BEAT_ACTION -> {
                    Log.e(TAG, "收到一个心跳包")
                }

                ClientService.MESSAGE_ACTION -> {
                    val message = intent.getStringExtra(ClientService.MESSAGE_ACTION)
                    val ip = intent.getStringExtra(ClientService.MESSAGE_USER)
                    Log.e(TAG, ip + " : " + message)
                    ToastU.showToast(ip + " : " + message)
                    val msg = MsgItem(false, ip,message)
                    msg.time=System.currentTimeMillis().toString()
                    mMsgList.add(0, msg)
                    initAdapter()
                }
                SimpleHttpServer.NEW_CLIENT -> {
                    val new_client = intent.getStringExtra(SimpleHttpServer.NEW_CLIENT)
                    ToastU.showToast("新客户端" + new_client)
                    if (!socketItemList.contains(new_client)) {
                        socketItemList.add(new_client)

                    }

                }
                ClientService.CONNECT_STATE -> {
                    val b = intent.getBooleanExtra(ClientService.CONNECT_STATE, false)
                    if (b) {
                        btn_ok.visibility = View.GONE
                        btn_cancel.visibility = View.VISIBLE
                        btn_cancel.setOnClickListener {
                            ToastU.showToast("btn_client_cancel")

                        }
                    } else {
                        btn_ok.visibility = View.VISIBLE
                        btn_cancel.visibility = View.GONE
                    }
                }
            }

        }
    }



}